import javax.servlet.MultipartConfigElement;
import javax.servlet.http.Part;
import java.io.File;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;

import com.google.gson.Gson;
import model.Result;

import static spark.Spark.*;

public class Main {

    private static Gson gson = new Gson();

    public static void main(String[] args) {
//        port(8080);
//        staticFileLocation("/public");
        File uploadDir = new File("E:/public/fuck");
        uploadDir.mkdir(); // create the upload directory if it doesn't exist
        externalStaticFileLocation("E:/public");
        imgprocess.Main imgproc = new imgprocess.Main();


        get("/hello", (request, response) -> "Hello World!");

        post("/hello", (request, response) ->
                "Hello World: " + request.body()
        );

        post("process", (req, res) -> {
            String name = req.queryParams("name");
            String method = req.queryParams("method");
            String processedName = null;

            switch (method) {
                case "salt":
                    Integer num = Integer.valueOf(req.queryParams("num"));
                    processedName = imgproc.salt(name, num);
                    break;
                case "blur":
                    processedName = imgproc.blur(name);
                    break;
                case "fudiao":
                    String type = req.queryParams("type");
                    System.out.println("1: " +type);
                    processedName = imgproc.fudiao(type, name);
                    break;
                case "erode":
                    processedName = imgproc.erode(name, Integer.valueOf(req.queryParams("threshold")), Integer.valueOf(req.queryParams("size")));
                    break;
                case "dilate":
                    processedName = imgproc.dilate(name, Integer.valueOf(req.queryParams("threshold")), Integer.valueOf(req.queryParams("size")));
                default:
                    break;
            }

            System.out.println(req.queryParams("name"));
//            String processedName = imgproc.blur(name);

            return gson.toJson(new Result(true, processedName));
        });


        post("/upload", (req, res) -> {

            Path tempFile = Files.createTempFile(uploadDir.toPath(), "", "");

            req.attribute("org.eclipse.jetty.multipartConfig", new MultipartConfigElement("/temp"));


            InputStream input = req.raw().getPart("img").getInputStream();
//            String name = req.raw().getPart("img").getContentType();
            Files.copy(input, tempFile, StandardCopyOption.REPLACE_EXISTING);


            return gson.toJson(new Result(true, tempFile.getFileName().toString()));

        });

    }
}
